package com.gao.sentinel.service.impl;

import com.gao.sentinel.common.Constants;
import com.gao.sentinel.mapper.ProductMapper;
import com.gao.sentinel.po.Product;
import com.gao.sentinel.service.ProductService;
import com.gao.sentinel.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 产品信息
 */
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private RedisUtil redisUtil;

    @Resource
    private ProductMapper productMapper;

    /**
     * 根据 ID 查询产品
     * @param productId
     * @return
     */
    @Override
    public Product queryProductInfo(Long productId) {
        Product product;
        // 从缓存中获取产品信息，从节点读数据
        Map<Object, Object> hmget = redisUtil.hmget(Constants.RedisKey.getProduct(productId));
        if (hmget.size() == 0) {
            product = productMapper.queryProductById(productId);
            Map<String, Object> productInfoMap = new HashMap();
            productInfoMap.put(productId.toString(), product);
            redisUtil.hmset(Constants.RedisKey.getProduct(productId), productInfoMap);
        } else {
            product = (Product) hmget.get(productId.toString());
        }
        return product;
    }

    /**
     * 查询所有产品
     * @return
     */
    @Override
    public List<Product> queryAllProductInfo() {
        return productMapper.queryAllProductInfo();
    }
}
